package com.kichina.galaxy.dev.tools.excel.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;



import com.kichina.galaxy.dev.tools.aliyun.model.util.AliyunThingModelUtil;
import com.kichina.galaxy.dev.tools.aliyun.model.bean.AliyunModelProperties;
import com.kichina.galaxy.dev.tools.aliyun.model.bean.DataSpecsModel;
import com.kichina.galaxy.dev.tools.aliyun.model.bean.ThingModelJsonModel;
import com.kichina.galaxy.dev.tools.excel.easyexcel.enums.PointEnum;
import com.kichina.galaxy.dev.tools.excel.easyexcel.model.ExcelModel;
import com.kichina.galaxy.dev.tools.logic.bean.IotDevicePointProtocol;
import com.kichina.galaxy.dev.tools.logic.service.IotDevicePointProtocolService;

import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.*;

// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
/**
 * @author Surging
 * @version 1.0
 * @ClassName AliyunThingModelUtil
 * @date 2022/6/8 22:22
 * @desc easyExcel回调类
 */
public class DemoDataListener extends AnalysisEventListener<ExcelModel> {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;
    List<ExcelModel> list = new ArrayList<ExcelModel>();

    List<IotDevicePointProtocol> devicePoints = Lists.newArrayList();
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private IotDevicePointProtocolService iotDevicePointProtocolService;





    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param iotDevicePointProtocolService
     */
    public DemoDataListener(IotDevicePointProtocolService iotDevicePointProtocolService) {
        this.iotDevicePointProtocolService = iotDevicePointProtocolService;
    }



    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ExcelModel data, AnalysisContext context) {
        //数据转换
        dataTransformation(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (devicePoints.size() >= BATCH_COUNT) {
            //保存数据
            saveData(devicePoints);
            // 存储完成清理 list
            devicePoints.clear();
        }
    }

    /**
     * @Author Surging
     * @Description Excel模型数据实体转换成数据库表数据实体
     * @param element Excel模型数据实体
     * @Return void
     * @Date  2022/6/14 19:44
     **/
    private void dataTransformation(ExcelModel element) {
        IotDevicePointProtocol devicePointProtocol = new IotDevicePointProtocol();
        BeanUtils.copyProperties(element, devicePointProtocol);
        if (PointEnum.ENUM_TYPE.getValue().equals(element.getType())) {
            devicePointProtocol.setPointType(0);
            devicePointProtocol.setDataType(0);
        } else if (PointEnum.STRING_TYPE.getValue().equals(element.getType())) {
            devicePointProtocol.setPointType(1);
            devicePointProtocol.setDataType(1);
        } else if (PointEnum.NUMBER_TYPE.getValue().equals(element.getType())) {
            devicePointProtocol.setPointType(1);
            devicePointProtocol.setDataType(0);
        }
        if (Objects.isNull(devicePointProtocol.getAcceptFormula())) {
            devicePointProtocol.setAcceptFormula("");
        }
        if (Objects.isNull(devicePointProtocol.getAgreementVersion())) {
            devicePointProtocol.setAcceptFormula("common-1.0");
        }
        if (Objects.isNull(devicePointProtocol.getAgreementVersion())) {
            devicePointProtocol.setAcceptFormula("common-1.0");
        }
        if (Objects.isNull(devicePointProtocol.getName())) {
            devicePointProtocol.setName("");
        }
        if (Objects.isNull(devicePointProtocol.getPointKey())) {
            devicePointProtocol.setPointKey("");
        }
        if (Objects.isNull(devicePointProtocol.getSendFormula())) {
            devicePointProtocol.setSendFormula("");
        }
        if (Objects.isNull(devicePointProtocol.getUnit())) {
            devicePointProtocol.setUnit("");
        }
        if (Objects.isNull(devicePointProtocol.getAcceptFormula())) {
            devicePointProtocol.setAcceptFormula("");
        }
        if (Objects.isNull(devicePointProtocol.getPointValueRange())) {
            devicePointProtocol.setPointValueRange("");
        }
        devicePointProtocol.setCreateTime(new Date());
        devicePointProtocol.setUpdateTime(new Date());
        devicePoints.add(devicePointProtocol);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData(devicePoints);
        // 存储完成清理 list
        devicePoints.clear();
    }

    /**
     * 加上存储数据库
     *
     * @param devicePoints
     */
    private void saveData(List<IotDevicePointProtocol> devicePoints){
        iotDevicePointProtocolService.saveBatch(devicePoints);
        if (Objects.nonNull(devicePoints)&& CollectionUtils.isNotEmpty(devicePoints)){
            String productKey = devicePoints.get(0).getProductKey();
            //构建物模型实体，添加物模型至物联网平台
            ThingModelJsonModel thingModelJsonModel = new ThingModelJsonModel();
            thingModelJsonModel.setProductKey(productKey);
            List<AliyunModelProperties> aliyunModelProperties = Lists.newArrayList();
            for (IotDevicePointProtocol devicePointProtocol : devicePoints) {
                AliyunModelProperties aliyng = new AliyunModelProperties();
                aliyng.setIdentifier(devicePointProtocol.getPointKey());
                aliyng.setRequired(false);
                aliyng.setRwFlag("READ_WRITE");
                aliyng.setName(devicePointProtocol.getName());
                aliyng.setCustomFlag(true);
                aliyng.setProductKey(productKey);
                if (0==devicePointProtocol.getPointType()&& 0== devicePointProtocol.getDataType()) {
                    aliyng.setDataType("ENUM");
                    List<DataSpecsModel> dataSpecsModels = Lists.newArrayList();
                    String[] splits = devicePointProtocol.getUnit().split(",");
                    for (String split : splits) {
                        String[] strings = split.split("-");
                        DataSpecsModel dataSpecs = new DataSpecsModel();
                        dataSpecs.setCustom(true);
                        dataSpecs.setDataType("ENUM");
                        dataSpecs.setValue(Integer.valueOf(strings[0]));
                        dataSpecs.setName(strings[1]);
                        dataSpecsModels.add(dataSpecs);
                    }
                    aliyng.setDataSpecsList(dataSpecsModels);
                } else if (1==devicePointProtocol.getPointType()&& 1== devicePointProtocol.getDataType()) {
                    Map<String, Object> dataSpecsMap = new HashMap<>();
                    aliyng.setDataType("TEXT");
                    dataSpecsMap.put("dataType","TEXT");
                    dataSpecsMap.put("length", 10240);
                    aliyng.setDataSpecs(dataSpecsMap);
                } else if (1==devicePointProtocol.getPointType()&& 0== devicePointProtocol.getDataType()) {
                    Map<String, Object> dataSpecsMap = new HashMap<>();
                    aliyng.setDataType("INT");
                    dataSpecsMap.put("dataType","INT");
                    if (Objects.nonNull(devicePointProtocol.getMaxValue())){
                        dataSpecsMap.put("max",devicePointProtocol.getMaxValue().toString());
                    }
                    if (Objects.nonNull(devicePointProtocol.getMinValue())){
                        dataSpecsMap.put("min",devicePointProtocol.getMinValue().toString());
                    }
                    if (Objects.nonNull(devicePointProtocol.getNumUnit())){
                        dataSpecsMap.put("unit",devicePointProtocol.getNumUnit());
                    }
                    aliyng.setDataSpecs(dataSpecsMap);
                }
                aliyunModelProperties.add(aliyng);
            }
            thingModelJsonModel.setProperties(aliyunModelProperties);
            try {
                //调用阿里物模型工具类添加属性
                AliyunThingModelUtil.addAliyunThingModel(thingModelJsonModel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}